module WsClient

	class Url
		attr_reader :scheme, :host, :resource_name
		
		def initialize(url)
			url = URI.parse(url)
			
			@scheme = url.scheme
			raise ArugmentError.new("Unknown scheme '#{@scheme}'") unless @scheme =~ /^wss?$/
			
			@host = url.host
			
			@port = if (port = url.port)
				if @scheme == 'ws' and port == 80
					nil
				elsif @scheme == 'wss' and port == 443
					nil
				else
					port
				end
			end
			
			@resource_name = url.path
		end
		
		def port
			if @port
				@port
			elsif @scheme == 'ws'
				80
			else
				443
			end
		end
		
		def secure?
			@scheme == 'wss'
		end
		
		def match?(url)
			self == WsClient::Url.new(url)
		end
		
		def to_s
			port = @port ? ":#{port}" : ''
			"#{@scheme}://#{@host}#{port}#{@resource_name || '/'}"
		end
		
		def ==(other)
			other.to_s == to_s
		end
	end

end
